package com.mathdroid.gui.main.character;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JPopupMenu;

import com.mathdroid.gui.ImageLoader;
import com.mathdroid.model.EModelObserverEvent;
import com.mathdroid.model.Model;
import com.mathdroid.model.enums.EItemSlot;
import com.mathdroid.model.enums.EModuleProficiency;
import com.mathdroid.model.items.Item;

/**
 * This context menu appears on right click on item slot buttons.
 */
public class ItemSlotContextMenu extends JPopupMenu {

	/**
	 * Default UID.
	 */
	private static final long serialVersionUID = 1L;
	
	/**
	 * The button to unequip items.
	 */
	private final JButton unequip = new JButton("Unequip");

	/**
	 * Create a context menu for item buttons.
	 * @param slot The slot of the item.
	 * @param module The module type of the item. Can be null.
	 * @param e The mouse event triggered.
	 */
	public ItemSlotContextMenu(final EItemSlot slot, 
			final EModuleProficiency module,
			final MouseEvent e) {
		super();
		
		this.setLayout(new GridBagLayout());
		
		final GridBagConstraints c = new GridBagConstraints();
		
		final int space = 2;
		c.insets = new Insets(space, space, space, space);
		
		this.unequip.setIcon(new ImageLoader().getImage("cross"));
		this.unequip.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(final ActionEvent a) {
				Item i = Model.getProfile().getEquipedItems().get(slot);
				
				if (i != null && module == null) {
					Model.getProfile().getEquipedItems().remove(slot);
				} else if (i != null && module != null) {
					Model.getProfile().getEquipedItems().get(slot)
					.getModules().put(module, null);
				}
				
				Model.fireEvent(EModelObserverEvent.EQUIPPED_ITEMS_CHANGED);
				setVisible(false);
			}
		});
		
		this.add(this.unequip, c);
		this.show(e.getComponent(), e.getX(), e.getY());
	}
}
